package com.feiyue.learning;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    private static final int THREAD_COUNT = 30;

    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    // 定义信号量，最多支持 10 个线程同时访问
    private static Semaphore s = new Semaphore(10);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try{
                        s.acquire();
                        // TODO 业务逻辑
                        System.out.println("save data");
                    } catch (InterruptedException e){}
                    finally {
                        s.release();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}
